<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <div class="banner-text">
          <h2 class="banner-title">欢迎回来，{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}！</h2>
          <p class="banner-subtitle">今天是 {{ currentDate }}，祝您工作愉快！</p>
        </div>
        <div class="banner-icon">
          <el-icon :size="80" color="#409eff"><Sunny /></el-icon>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" v-for="(stat, index) in statCards" :key="index">
        <div class="stat-card-wrapper" :style="{ animationDelay: `${index * 0.1}s` }">
          <el-card class="stat-card" :class="stat.cardClass" shadow="hover">
            <div class="stat-item">
              <div class="stat-icon" :class="stat.iconClass">
                <el-icon :size="48"><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
                <div class="stat-detail" v-if="stat.details">
                  <span v-for="(detail, i) in stat.details" :key="i" :class="detail.class">
                    {{ detail.label }}: {{ detail.value }}
                  </span>
                </div>
              </div>
            </div>
            <div class="stat-decoration"></div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon :size="20" color="#409eff"><DataAnalysis /></el-icon>
              <span>用户状态分布</span>
            </div>
          </template>
          <div ref="userStatusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon :size="20" color="#67c23a"><DataAnalysis /></el-icon>
              <span>系统数据统计</span>
            </div>
          </template>
          <div ref="systemDataChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作和日志统计 -->
    <el-row :gutter="20" class="content-row">
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="quick-action-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon :size="20" color="#409eff"><Operation /></el-icon>
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <div
              v-for="action in quickActions"
              :key="action.path"
              class="action-item"
              @click="$router.push(action.path)"
            >
              <div class="action-icon" :style="{ background: action.color }">
                <el-icon :size="24"><component :is="action.icon" /></el-icon>
              </div>
              <span class="action-label">{{ action.label }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="log-stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon :size="20" color="#67c23a"><DataAnalysis /></el-icon>
              <span>数据统计</span>
            </div>
          </template>
          <el-descriptions :column="1" border class="stat-descriptions">
            <el-descriptions-item label="操作日志">
              <el-tag type="info" effect="plain">{{ statistics.operation_logs || 0 }} 条</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="登录日志">
              <el-tag type="warning" effect="plain">{{ statistics.login_logs || 0 }} 条</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="部门总数">
              <el-tag type="success" effect="plain">{{ statistics.departments?.total || 0 }}</el-tag>
              <el-tag size="small" type="success" style="margin-left: 10px">
                启用: {{ statistics.departments?.enabled || 0 }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, computed, onMounted, onUnmounted, ref, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import * as echarts from 'echarts'
import {
  User,
  UserFilled,
  Menu,
  Monitor,
  Operation,
  DataAnalysis,
  Sunny,
  Setting,
  Document,
  View,
} from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()

const statistics = reactive({
  users: {},
  roles: {},
  menus: {},
  departments: {},
  online_users: 0,
  operation_logs: 0,
  login_logs: 0,
})

const userStatusChartRef = ref(null)
const systemDataChartRef = ref(null)
let userStatusChart = null
let systemDataChart = null

const currentDate = computed(() => {
  const date = new Date()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const weekday = weekdays[date.getDay()]
  return `${year}年${month}月${day}日 ${weekday}`
})

const statCards = computed(() => {
  return [
    {
      icon: User,
      iconClass: 'user-icon',
      cardClass: 'user-card',
      value: statistics.users?.total || 0,
      label: '用户总数',
      details: [
        { label: '启用', value: statistics.users?.enabled || 0, class: 'success' },
        { label: '禁用', value: statistics.users?.disabled || 0, class: 'danger' },
      ],
    },
    {
      icon: UserFilled,
      iconClass: 'role-icon',
      cardClass: 'role-card',
      value: statistics.roles?.total || 0,
      label: '角色总数',
      details: [{ label: '启用', value: statistics.roles?.enabled || 0, class: 'success' }],
    },
    {
      icon: Menu,
      iconClass: 'menu-icon',
      cardClass: 'menu-card',
      value: statistics.menus?.total || 0,
      label: '菜单总数',
      details: [{ label: '启用', value: statistics.menus?.enabled || 0, class: 'success' }],
    },
    {
      icon: Monitor,
      iconClass: 'online-icon',
      cardClass: 'online-card',
      value: statistics.online_users || 0,
      label: '在线用户',
      details: [{ label: '实时在线', value: '', class: 'info' }],
    },
  ]
})

const quickActions = [
  { path: '/system/user', label: '用户管理', icon: User, color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
  { path: '/system/role', label: '角色管理', icon: UserFilled, color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' },
  { path: '/system/menu', label: '菜单管理', icon: Menu, color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)' },
  { path: '/monitor/system', label: '系统监控', icon: Monitor, color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)' },
  { path: '/monitor/operation-log', label: '操作日志', icon: Document, color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)' },
  { path: '/profile', label: '个人中心', icon: Setting, color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)' },
]

// 加载统计数据
const loadStatistics = async () => {
  try {
    const res = await request.get('/system/statistics')
    if (res.code === 200) {
      Object.assign(statistics, res.data)
      // 数据加载后更新图表，等待DOM渲染
      await nextTick()
      setTimeout(() => {
        initCharts()
      }, 200)
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 初始化图表
const initCharts = () => {
  if (!userStatusChartRef.value || !systemDataChartRef.value) {
    // 如果DOM还未渲染，延迟初始化
    setTimeout(() => {
      if (userStatusChartRef.value && systemDataChartRef.value) {
        initCharts()
      }
    }, 100)
    return
  }

  // 用户状态分布饼图
  if (!userStatusChart) {
    userStatusChart = echarts.init(userStatusChartRef.value)
  }
  
  const userStatusOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用户状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}\n({d}%)'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: [
          { value: statistics.users?.enabled || 0, name: '启用', itemStyle: { color: '#67c23a' } },
          { value: statistics.users?.disabled || 0, name: '禁用', itemStyle: { color: '#f56c6c' } }
        ]
      }
    ]
  }
  userStatusChart.setOption(userStatusOption)

  // 系统数据统计柱状图
  if (!systemDataChart) {
    systemDataChart = echarts.init(systemDataChartRef.value)
  }
  
  const systemDataOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['用户', '角色', '菜单', '部门', '在线用户'],
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        },
        data: [
          statistics.users?.total || 0,
          statistics.roles?.total || 0,
          statistics.menus?.total || 0,
          statistics.departments?.total || 0,
          statistics.online_users || 0
        ]
      }
    ]
  }
  systemDataChart.setOption(systemDataOption)

  // 窗口大小改变时调整图表
  window.addEventListener('resize', () => {
    userStatusChart?.resize()
    systemDataChart?.resize()
  })
}

// 监听统计数据变化，更新图表
watch(
  () => statistics,
  () => {
    if (userStatusChart && systemDataChart) {
      initCharts()
    }
  },
  { deep: true }
)

onMounted(() => {
  loadStatistics()
})

// 组件卸载时销毁图表
onUnmounted(() => {
  userStatusChart?.dispose()
  systemDataChart?.dispose()
  window.removeEventListener('resize', () => {
    userStatusChart?.resize()
    systemDataChart?.resize()
  })
})
</script>

<style scoped lang="scss">
.dashboard-container {
  // padding 由 app-container 统一管理
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 欢迎横幅
.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 24px;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
  animation: slideInDown 0.6s ease-out;

  .banner-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .banner-text {
    color: #fff;

    .banner-title {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 8px;
    }

    .banner-subtitle {
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .banner-icon {
    animation: rotate 10s linear infinite;
  }
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 统计卡片
.stats-row {
  margin-bottom: 24px;
}

.stat-card-wrapper {
  animation: fadeInUp 0.6s ease-out both;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  position: relative;
  overflow: hidden;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
  }

  .stat-item {
    display: flex;
    align-items: center;
    position: relative;
    z-index: 2;
  }

  .stat-icon {
    width: 70px;
    height: 70px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    transition: all 0.3s ease;

    &.user-icon {
      background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
      color: #2196f3;
    }

    &.role-icon {
      background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
      color: #9c27b0;
    }

    &.menu-icon {
      background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
      color: #4caf50;
    }

    &.online-icon {
      background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
      color: #ff9800;
    }
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 32px;
      font-weight: 700;
      color: #303133;
      margin-bottom: 8px;
      line-height: 1;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .stat-detail {
      font-size: 12px;
      display: flex;
      gap: 12px;
      flex-wrap: wrap;

      .success {
        color: #67c23a;
        font-weight: 500;
      }

      .danger {
        color: #f56c6c;
        font-weight: 500;
      }

      .info {
        color: #909399;
      }
    }
  }

  .stat-decoration {
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    pointer-events: none;
  }

  &:hover .stat-icon {
    transform: scale(1.1) rotate(5deg);
  }
}

// 图表区域
.chart-row {
  margin-top: 24px;
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 12px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    font-size: 16px;
  }
}

.chart-container {
  width: 100%;
  height: 300px;
}

// 内容区域
.content-row {
  margin-top: 24px;
}

.quick-action-card,
.log-stat-card {
  border-radius: 12px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    font-size: 16px;
  }
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  // padding 由 app-container 统一管理
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f5f7fa;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #fff;
  }

  .action-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    margin-bottom: 4px;
  }

  .action-label {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
  }
}

.stat-descriptions {
  :deep(.el-descriptions__label) {
    font-weight: 500;
    color: #606266;
  }

  :deep(.el-descriptions__content) {
    color: #303133;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 15px;
  }

  .welcome-banner {
    // padding 由 app-container 统一管理

    .banner-content {
      flex-direction: column;
      text-align: center;
      gap: 20px;
    }

    .banner-title {
      font-size: 22px;
    }
  }

  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }

  .stat-card {
    .stat-item {
      flex-direction: column;
      text-align: center;
    }

    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }

  .chart-container {
    height: 250px;
  }
}
</style>

